package com.wswy.wzcx.ui.wzdb

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.view.View
import android.view.ViewGroup
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.adapter.SampleRecyclerViewAdapter
import com.che.libcommon.ui.loading.ILoadingView
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.InternalMsgCodeKt
import com.wswy.wzcx.module.base.*
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.data.WZDBMode
import com.wswy.wzcx.ui.fragment.WZDBSubmitFragment
import com.wswy.wzcx.ui.other.CloseDelegate
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.ui.pay.PayOrder
import com.wswy.wzcx.ui.pay.PayWzdbData
import com.wswy.wzcx.utils.StringUtils
import kotlinx.android.synthetic.main.fragment_wzdb_pick.*
import kotlinx.android.synthetic.main.item_wzdb_pick_layout.view.*

class WzdbPickFragment : CBaseLoadingFragment() {

    companion object{

        const val TAG = "WzdbPickFragment"

        @JvmStatic
        fun newInstance(bundle: Bundle?) = WzdbPickFragment().apply {
            arguments = bundle
        }
    }

    override fun getConfigure(): ILoadingView.LoadingConfigure? {
        return null
    }

    override fun getLoadingFrameId(): Int {
        return R.id.root_content
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_wzdb_pick
    }

    override fun getFragmentTitle(): String {
        return "选择代办条目"
    }


    private lateinit var wzdbViewModel: WzdbViewModel
    private lateinit var adapter :WzPickAdapter

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        wzdbViewModel = provideViewModel(WzdbViewModel::class.java)
        wzdbViewModel.onCreate()

        arguments?.getParcelable<UserCarInfo?>(Constants.EXTRA_DATA)?.let {

            wzdbViewModel.userCarInfo = it

            wzdbViewModel.defaultChooseUid = arguments?.getString("defaultChoose",null)

            wzdbViewModel.loadList()


            initViews()

        }?:kotlin.run {
            finish()
            return
        }


    }

    private fun initViews(){

        registerEvent(InternalMsgCode.CODE_PAY_SUCCESS){
            finish()
        }

        btn_next_step.onClick {

            wzdbViewModel.submitWz(adapter.selectedUid.values.map { it.uniquerMd5Id }.joinToString(","))

        }

        img_float_wechatservice.onClick {

            DialogFactory.showTelHelp(it.getContext(), getString(R.string.wzdb_tel))
        }

        adapter = WzPickAdapter{
            //选择
            var points = 0
            adapter.selectedUid.values.forEach {
                it.deductPoint?.let {
                    points +=it
                }
            }
            btn_next_step.isEnabled = points < 12 && adapter.selectedUid.isNotEmpty()

            if (points > 11 ){
                fl_bottom_hint.visible()
            }else{
                fl_bottom_hint.gone()
            }
            //
        }

        adapter.onAddCallback = {

            var points = 0
            adapter.selectedUid.values.forEach {

                it.deductPoint?.let {
                    points +=it
                }
            }
            points < 12
        }

        recycler_view.layoutManager = LinearLayoutManager(requireContext())
        recycler_view.adapter = adapter

        wzdbViewModel.getWzListLiveData().observe(this, Observer {

            it?.runCatching {

                if(inLoading()){
                    showLoading(true)
                }else{

                    if(isOk() && data?.isNotEmpty() == true){
                        //有数据

                        val list = ArrayList<WZDBMode>()
                        data.let {
                            list.addAll(it)
                        }

                        var defWZ:WZDBMode?=null
                        if (!wzdbViewModel.defaultChooseUid.isNullOrEmpty()){
                            var idx = -1
                            list.forEachIndexed { index, wzdbMode ->
                                if (TextUtils.equals(wzdbMode.uniquerMd5Id,wzdbViewModel.defaultChooseUid)){
                                    idx = index
                                    return@forEachIndexed
                                }
                            }

                            if (idx != -1){
                                list.removeAt(idx).let {
                                    defWZ = it
                                    list.add(0,it)
                                }
                            }
                        }

                        showData()
                        adapter.setNewData(list)
                        adapter.notifyDataSetChanged()

                        val defUid = wzdbViewModel.defaultChooseUid
                        if(defUid != null && defWZ != null){
                            adapter.setUnid(defUid,defWZ!!)
                        }


                    }else{
                        //空

                        showError(VOMessage.createEmpty(R.drawable.mycar_empty_default, R.string.empty_wzdb_fines, 0))

                    }

                }

            }
        })

        // 提交订单

        wzdbViewModel.getWzdbCreateLiveData().observe(this, Observer {

            it?.runCatching {

                if (inLoading()){

                }else{

                    if (isOk()){
                        //提交成功
                        if(data?.orderInfo != null){
                            //不需要资料
                            RouterUtils.startPage(context, RPaths.PAY_ORDER,Bundle().apply {
                                putParcelable(Constants.EXTRA_DATA, PayOrder(PayOrder.TYPE_WZDB, PayWzdbData(data.orderInfo,wzdbViewModel.userCarInfo)))
                            })

                        }else if (data?.list?.isNotEmpty() == true){
                            //补充资料
                            WZDBSubmitCertActivity.start(context, data.listIds!!, data.list!!,wzdbViewModel.userCarInfo)
                        }


                    }else{

                        ToastUtils.showText(message?:"提交失败，请返回重试")
                    }

                }


            }
        })
    }

    private class WzPickAdapter(private val onSelectedCallback:(()->Unit)? ) : SampleRecyclerViewAdapter<WZDBMode, WzPickAdapter.WzPickViewHolder>() {
        val selectedUid = HashMap<String,WZDBMode>()

        var onAddCallback:((WZDBMode)->Boolean)? = null


        fun setUnid(unid:String,wzdbMode: WZDBMode){
            if (onAddCallback?.invoke(wzdbMode) == true){
                selectedUid.put(unid,wzdbMode)

                onSelectedCallback?.invoke()
                notifyDataSetChanged()
            }
        }

        init {
            setOnItemClickListener { _, position, t ->
                t?.uniquerMd5Id?.also {

                    if (selectedUid.containsKey(it)){
                        //已有 删除
                        selectedUid.remove(it)
                        notifyItemChanged(position)
                    }else{
                        if (onAddCallback?.invoke(t) == true){
                            selectedUid.put(it,t)
                            notifyItemChanged(position)
                        }
                    }
                }

                onSelectedCallback?.invoke()
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, p1: Int): WzPickViewHolder {
            return WzPickViewHolder(loadLayout(parent,R.layout.item_wzdb_pick_layout))
        }


        override fun onBindViewHolder(holder: WzPickViewHolder, position: Int, data: WZDBMode?) {
            data?.run {
                holder.itemView.tv_fine_info.text = weiFaXinWeiMingCheng
                holder.itemView.tv_fine_addr.text = weiFaDiZhi
                holder.itemView.tv_fine_time.text = weiFaSheJiang
                holder.itemView.tv_fine_fee.text = SpannableStringBuilder().apply {
                    //"罚款 ${StringUtils.formatMoney(data.faKuanJinHe)}"
                    append(SpannableString("罚款 ").apply {
                        setSpan(RelativeSizeSpan(0.8f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                    append(SpannableString(StringUtils.formatMoney(data.faKuanJinHe)).apply {
                        setSpan(ForegroundColorSpan(ContextCompat.getColor(holder.itemView.context,R.color.accentColor3)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                }
                holder.itemView.tv_fine_points.text = SpannableStringBuilder().apply {
                    //"罚款 ${StringUtils.formatMoney(data.faKuanJinHe)}"
                    append(SpannableString("扣分 ").apply {
                        setSpan(RelativeSizeSpan(0.8f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                    append(SpannableString("${deductPoint?:0}").apply {
                        setSpan(ForegroundColorSpan(ContextCompat.getColor(holder.itemView.context,R.color.accentColor3)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                }
                //holder.itemView.tv_fine_points.text = "扣分 ${deductPoint?:0}"
                holder.itemView.tv_service_fee.text = "服务费 ${StringUtils.formatMoney(data.daiBanFei)}"
                holder.itemView.img_choose.isSelected = selectedUid.containsKey(uniquerMd5Id)
            }
        }

        class WzPickViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    }



}